package org.jetlinks.pro.visualization.service;

import lombok.AllArgsConstructor;
import org.hswebframework.web.crud.events.EntityBeforeDeleteEvent;
import org.hswebframework.web.crud.events.EntityDeletedEvent;
import org.hswebframework.web.exception.BusinessException;
import org.jetlinks.pro.visualization.entity.DataVisualizationEntity;
import org.jetlinks.pro.visualization.entity.VisualizationCatalogEntity;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class VisualizationEntityDeleteEventHandler {

    private final DataVisualizationService visualizationService;


    @EventListener
    public void handleVisualizationCatalogDelete(EntityBeforeDeleteEvent<VisualizationCatalogEntity> event) {

        event.async(
            visualizationService
                .createQuery()
                .in(DataVisualizationEntity::getCatalogId, event
                    .getEntity()
                    .stream()
                    .map(VisualizationCatalogEntity::getId)
                    .collect(Collectors.toList()))
                .count()
                .doOnNext(i -> {
                    if (i > 0) {
                        throw new BusinessException("error.vis_catalog_has_bean_use_by_config");
                    }
                })
        );

    }

}
